<template>
  <div class="app-container">
    <!-- 基础信息卡片 -->
    <el-card class="base-info-card" shadow="never">
      <div slot="header" class="base-info-title">
        <span>基础信息</span>
      </div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="140px" size="small" class="base-info-form">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="出库单编号" prop="sales_code">
              <div class="input-switch-group">
                <el-input v-model="form.sales_code" placeholder="自动生成编号" :readonly="form.auto_code" />
                <el-switch v-model="form.auto_code" style="margin-left: 8px;" @change="handleAutoCodeChange" />
                <span class="switch-label">自动生成</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库单名称" prop="sales_name">
              <el-input v-model="form.sales_name" placeholder="请输入出库单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户" prop="customer_name">
              <el-input v-model="form.customer_name" placeholder="请输入客户" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="销售订单" prop="order_code">
              <el-input v-model="form.order_code" placeholder="请选择销售订单" readonly>
                <template slot="append">
                  <el-button icon="el-icon-search" @click="handleOpenOrderDialog" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货人" prop="recipient">
              <el-input v-model="form.recipient" placeholder="请输入收货人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="16">
            <el-form-item label="收货地址" prop="region">
              <div style="display: flex; gap: 10px;">
                <el-cascader
                  v-model="form.region"
                  :options="pcaTextArr"
                  placeholder="请选择省/市/区"
                  clearable
                  size="small"
                  style="width: 50%;"
                />
                <el-input v-model="form.address" placeholder="请输入详细地址" style="width: 50%;" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="承运商" prop="carrier">
              <el-select v-model="form.carrier" placeholder="请选择承运商" filterable allow-create>
                <el-option
                  v-for="item in carrierOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="运输单号" prop="shipping_number">
              <el-input v-model="form.shipping_number" placeholder="请输入运输单号" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <!-- 预留位置，可以根据需要添加其他字段 -->
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 出库物料明细 -->
    <div class="goods-section">
      <div style="margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;">
        <span style="font-weight: bold;">出库产品明细</span>
      </div>
      <el-table :data="pagedItemList" style="width: 100%" border>
        <el-table-column prop="product_code" label="产品编号" align="center" width="300" />
        <el-table-column prop="product_name" label="产品名称" align="center" show-overflow-tooltip />
        <el-table-column prop="stock_sfn" label="规格型号" align="center" width="230" show-overflow-tooltip />
        <el-table-column prop="unit" label="单位" align="center" width="160" />
        <el-table-column prop="sales_num" label="出库数量" align="center" width="160" />
        <el-table-column prop="remark" label="备注" align="center" width="450" />
      </el-table>
      <!-- 添加物料明细的分页组件 -->
      <div style="margin: 16px 0; text-align: right;">
        <pagination
          v-show="totalItems > 0"
          :total="totalItems"
          :page.sync="itemQuery.pageNum"
          :limit.sync="itemQuery.pageSize"
          @pagination="handleItemPagination"
          :noScroll="true"
        />
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div style="margin-top: 30px; text-align: center;">
      <el-button type="primary" @click="handleSubmit">保存</el-button>
      <el-button type="success" @click="handleSubmitAndApprove">保存并提交</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>

    <!-- 销售订单选择弹窗 -->
    <el-dialog title="选择销售订单" :visible.sync="orderDialogVisible" width="1200px">
      <div style="margin-bottom: 10px; display: flex; gap: 10px;">
        <el-input v-model="orderQuery.order_code" placeholder="请输入订单编号" size="small" style="width: 180px;" />
        <el-input v-model="orderQuery.customer_name" placeholder="请输入客户名称" size="small" style="width: 180px;" />
        <el-button type="primary" size="small" @click="handleOrderSearch">搜索</el-button>
        <el-button size="small" @click="handleOrderReset">重置</el-button>
      </div>
      <el-table 
        :data="orderList" 
        style="width: 100%" 
        border 
        @row-click="selectOrderAndClose" 
        highlight-current-row
      >
        <el-table-column prop="order_code" label="订单编号" align="center" width="160" show-overflow-tooltip/>
        <el-table-column prop="customer_name" label="客户名称" align="center" width="260" show-overflow-tooltip/>
        <el-table-column prop="order_date" label="订单日期" align="center" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.order_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="delivery_date" label="交付日期" align="center" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.delivery_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip/>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
              {{ scope.row.status === '1' ? '已确定' : '未确定' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 16px 0; text-align: right;">
        <pagination
          v-show="orderQuery.total > 0"
          :total="orderQuery.total"
          :page.sync="orderQuery.pageNum"
          :limit.sync="orderQuery.pageSize"
          @pagination="getOrderList"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 导入区域数据
import { pcaTextArr } from 'element-china-area-data'
import Pagination from "@/components/Pagination"
import { addOutbound,selectSalesOrder,selectSalesOrderDetail,getOutbound } from "@/views/ck/js/outbound"
import { listCustomer } from "@/api/basic/customer"
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";

export default {
  name: 'AddOutbound',
  components: {
    Pagination
  },
  data() {
    return {
      // 出库单表单数据
      form: {
        sales_id: '', // 出库单ID
        sales_code: '', // 出库单编号
        auto_code: true, // 是否自动生成编号
        sales_name: '', // 出库单名称
        
        customer_id: '', // 客户ID
        customer_code: '', // 客户编码
        customer_name: '', // 客户名称
        recipient: '', // 收货人
        tel: '', // 联系电话
        
        region: [], // 省市区
        address: '', // 收货地址
        carrier: '', // 承运商
        shipping_number: '', // 运输单号
        
        sales_order_id: '', // 销售订单ID
        order_code: '', // 销售订单编号

        status: '1', // 状态默认待提交
        
        remark: '', // 备注
        create_by: '', // 创建人
        update_by: '' // 更新人
      },
      // 表单验证规则
      rules: {
        sales_code: [
          { required: true, message: '请生成出库单编号', trigger: ['blur', 'change'] }
        ],
        sales_name: [
          { required: true, message: '请输入出库单名称', trigger: 'blur' }
        ],
        customer_name: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        recipient: [
          { required: true, message: '请输入收货人', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请选择所在地区', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        order_code: [
          { required: true, message: '请选择销售订单', trigger: 'change' }
        ],
        carrier: [
          { required: true, message: '请输入承运商', trigger: 'blur' }
        ],
        shipping_number: [
          { required: true, message: '请输入运输单号', trigger: 'blur' }
        ]
      },
      
      // 出库物料明细
      itemList: [], // 存储所有产品数据
      // 物料明细分页
      itemQuery: {
        pageNum: 1,
        pageSize: 10
      },
      
      // 承运商选项
      carrierOptions: [
        { value: '顺丰物流', label: '顺丰物流' },
        { value: '中通快递', label: '中通快递' },
        { value: '圆通速递', label: '圆通速递' },
        { value: '申通快递', label: '申通快递' },
        { value: '韵达快递', label: '韵达快递' },
        { value: '百世快递', label: '百世快递' },
        { value: '邮政快递', label: '邮政快递' },
        { value: '德邦物流', label: '德邦物流' },
        { value: '京东物流', label: '京东物流' },
        { value: '天天快递', label: '天天快递' },
        { value: '极兔速递', label: '极兔速递' },
        { value: '菜鸟物流', label: '菜鸟物流' },
        { value: '安能物流', label: '安能物流' },
        { value: '苏宁物流', label: '苏宁物流' },
        { value: 'FedEx联邦', label: 'FedEx联邦' },
        { value: '速尔快递', label: '速尔快递' },
        { value: '优速物流', label: '优速物流' }
      ],
      // 使用导入的省市区数据
      pcaTextArr,
      // 商品库存数据（批次等信息）
      inventoryData: [],
      // 出库商品选择对话框
      goodsDialogVisible: false,
      goodsList: [],
      goodsLoading: false,
      goodsQuery: {
        sales_order_id: '',
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      selectedGoods: [], // 已选择商品数组


      // 销售订单选择对话框
      orderDialogVisible: false,
      orderList: [],
      orderQuery: {
        pageNum: 1,
        pageSize: 10,
        order_code: '',
        customer_name: '',
        total: 0
      },
    }
  },
  computed: {
    // 计算属性，根据当前分页获取物料明细数据
    pagedItemList() {
      const start = (this.itemQuery.pageNum - 1) * this.itemQuery.pageSize;
      const end = start + this.itemQuery.pageSize;
      return this.itemList.slice(start, end);
    },
    // 计算总页数
    totalItems() {
      return this.itemList.length;
    }
  },
  created() {
    // 从路由查询字符串中获取数据 修改出库单
    if(this.$route.query.order != undefined){
      this.form = JSON.parse(this.$route.query.order);
      console.log("form:",this.form);
      
      // 如果有地址信息，解析并填充省市区和详细地址
      if(this.form.address) {
        this.parseAndFillAddress(this.form.address);
      }
      
      // 如果有销售订单编号，获取销售产品信息
      if(this.form.sales_order_id) {
        this.loadOrderProductsByOrderId(this.form.sales_order_id);
      }
    }else{
      // 如果是自动生成编号，获取编号
    if (this.form.auto_code) {
      this.getAutoCode();
    }
    }
    
    
    //this.selectedGoods = []; // 初始化已选择商品数组
    //this.getInventoryData(); // 获取库存数据
  },
  methods: {
    /**
     * 解析完整地址并填充省市区和详细地址
     * @param {String} fullAddress 完整地址，如"天津市市辖区河西区营盘路36号"
     */
    parseAndFillAddress(fullAddress) {
      if (!fullAddress) return;
      
      // 所有省份列表
      const provinces = this.pcaTextArr.map(p => p.label);
      
      // 尝试查找省份
      let province = null;
      let provinceIndex = -1;
      for (let i = 0; i < provinces.length; i++) {
        if (fullAddress.startsWith(provinces[i])) {
          province = provinces[i];
          provinceIndex = i;
          break;
        }
      }
      
      if (province === null) return; // 没找到省份
      
      // 从地址中移除省份
      let remainingAddress = fullAddress.substring(province.length);
      
      // 获取该省下的所有市
      const cities = this.pcaTextArr[provinceIndex].children.map(c => c.label);
      
      // 查找市
      let city = null;
      let cityIndex = -1;
      for (let i = 0; i < cities.length; i++) {
        if (remainingAddress.startsWith(cities[i])) {
          city = cities[i];
          cityIndex = i;
          break;
        }
      }
      
      if (city === null) return; // 没找到市
      
      // 从地址中移除市
      remainingAddress = remainingAddress.substring(city.length);
      
      // 获取该市下的所有区/县
      const districts = this.pcaTextArr[provinceIndex].children[cityIndex].children.map(d => d.label);
      
      // 查找区/县
      let district = null;
      for (let i = 0; i < districts.length; i++) {
        if (remainingAddress.startsWith(districts[i])) {
          district = districts[i];
          break;
        }
      }
      
      if (district === null) return; // 没找到区/县
      
      // 从地址中移除区/县，剩下的就是详细地址
      remainingAddress = remainingAddress.substring(district.length);
      
      // 设置省市区到表单的region字段
      this.form.region = [province, city, district];
      
      // 设置详细地址
      this.form.address = remainingAddress.trim();
      
      console.log("已解析地址：", {
        region: this.form.region,
        address: this.form.address
      });
    },

    /**
     * 获取库存批次数据
     */
    getInventoryData() {
      const params = {
        pageNum: 1,
        pageSize: 1000 // 先获取足够多的数据
      };
      
      selectSalesOrderDetail(params).then(response => {
        this.inventoryData = response.rows || [];
      }).catch(error => {
        console.error('获取库存数据失败:', error);
        this.$message.error('获取库存数据失败');
      });
    },

    /**
     * 计算物料行的总价
     * @param {Object} row 物料行数据
     * @return {String} 格式化后的总价
     */
    calculateTotalPrice(row) {
      const qty = Number(row.outbound_qty) || 0;
      const price = Number(row.unit_price) || 0;
      const total = Math.round(qty * price * 100) / 100;
      row.total_price = total.toFixed(2);
      return total.toFixed(2);
    },
    
    /**
     * 处理物料明细分页变化
     * @param {Object} val 分页信息
     */
    handleItemPagination(val) {
      // 阻止默认事件可能引起的滚动
      if (event) {
        event.preventDefault();
      }
      
      // 精确保存当前滚动位置
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
      
      // 更新分页参数（现在仅用于前端分页）
      this.itemQuery.pageNum = val.page;
      this.itemQuery.pageSize = val.limit;
      
      // 显示小型加载指示器
      const loading = this.$loading({
        lock: false,
        text: '加载中...',
        spinner: 'el-icon-loading',
        customClass: 'mini-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      });
      
      // 立即恢复滚动位置，防止任何可能的滚动
      window.scrollTo(scrollLeft, scrollTop);
      
      // 前端分页不需要请求后台，直接关闭loading
      loading.close();
      
      // 使用多重保障确保滚动位置不变
      this.$nextTick(() => {
        window.scrollTo(scrollLeft, scrollTop);
        
        // 延迟再次检查并恢复滚动位置
        setTimeout(() => {
          window.scrollTo(scrollLeft, scrollTop);
        }, 10);
      });
      
      // 防止事件冒泡可能引起的滚动
      return false;
    },
    
    /**
     * 获取客户列表
     */
    getCustomerList() {
      listCustomer().then(response => {
        this.customerOptions = response.rows || [];
      }).catch(error => {
        console.error('获取客户列表失败:', error);
        this.$message.error('获取客户列表失败');
      });
    },
    
    /**
     * 处理客户变更
     */
    handleCustomerChange(customerId) {
      // 找到对应的客户信息
      const customer = this.customerOptions.find(item => item.customer_id === customerId);
      if (customer) {
        this.form.customer_name = customer.customer_name;
        this.form.customer_code = customer.customer_code || '';
        
        // 可以自动填充收货地址和联系人等信息
        this.form.address = customer.address || '';
        this.form.recipient = customer.contact_person || '';
        this.form.tel = customer.contact_number || '';
      }
    },
    
    /**
     * 获取完整地址
     */
    getFullAddress() {
      // 如果没有选择地区，直接返回详细地址
      if (!this.form.region || this.form.region.length === 0) {
        return this.form.address;
      }
      
      // 组合省市区和详细地址
      return this.form.region.join(' ') + ' ' + this.form.address;
    },
    
    /**
     * 处理表单提交
     */
    async handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;
        
        // 检查是否有物料行
        if (this.itemList.length === 0) {
          this.$message.warning('请添加出库产品');
          return;
        }
        
        // 显示提交中的加载状态
        const loading = this.$loading({
          lock: true,
          text: '正在保存数据，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        // 设置创建人和更新人
        this.form.create_by = this.$store.getters.name;
        this.form.update_by = this.form.create_by;
        
        // 组装完整地址
        const fullAddress = this.getFullAddress();
        const submitForm = { ...this.form, address: fullAddress };
        
        // 如果是自动生成编号，并且是新增状态，则消费编号
        if (this.form.auto_code && !this.form.sales_id) {
          try {
            const res = await getAutoNumbersConsume(35);
            if (res.code === 200) {
              submitForm.sales_code = res.msg;
            } else {
              this.$message.error(res.msg || '获取最终编号失败');
              loading.close();
              return;
            }
          } catch (err) {
            this.$message.error('获取最终编号请求异常');
            loading.close();
            return;
          }
        }

        // 构造提交数据
        const submitData = {
          sales: submitForm,
          lines: this.itemList
        };
        console.log("测试提交的数据：",submitData);
        
        // 调用后端接口保存数据
        addOutbound(submitData).then(response => {
          loading.close();
          if (response.code === 200) {
            this.$message.success('出库单创建成功');
            this.$router.push('/ck/SalesOutbound');
          } else {
            this.$message.error(response.msg || '出库单创建失败');
        }
        }).catch(error => {
          loading.close();
          console.error('创建出库单失败:', error);
          //this.$message.error('系统错误，请稍后重试');
        });
      });
    },
    
    /**
     * 保存并提交审核
     */
    handleSubmitAndApprove() {
      this.form.status = '2'; // 设置状态为待质检
      this.handleSubmit();
    },
    
    /**
     * 取消操作
     */
    handleCancel() {
      this.$router.back();
    },
    
    /**
     * 处理自动生成编号开关变化
     */
    handleAutoCodeChange(val) {
      if (val) {
        this.getAutoCode();
      } else {
        this.form.sales_code = '';
      }
    },
    
    /**
     * 获取自动生成的编号
     */
    getAutoCode() {
      getAutoNumbers(35).then(res => { // 35 是出库单的编号类型
        if (res.code === 200) {
          this.form.sales_code = res.msg;
        } else {
          this.$message.error(res.msg || '获取编号失败');
          this.form.auto_code = false;
        }
      }).catch(err => {
        this.$message.error('获取编号请求异常');
        this.form.auto_code = false;
      });
    },
    
    /**
     * 打开销售订单选择对话框
     */
    handleOpenOrderDialog() {
      this.orderDialogVisible = true;
      this.getOrderList();
    },

    /**
     * 获取销售订单列表
     */
    getOrderList() {
      selectSalesOrder(this.orderQuery).then(response => {
        this.orderList = response.rows || [];
        this.orderQuery.total = response.total || 0;
      }).catch(error => {
        console.error('获取销售订单列表失败:', error);
        this.$message.error('获取销售订单列表失败');
      });
    },

    /**
     * 搜索销售订单
     */
    handleOrderSearch() {
      this.orderQuery.pageNum = 1;
      this.getOrderList();
    },

    /**
     * 重置销售订单搜索条件
     */
    handleOrderReset() {
      this.orderQuery = {
        pageNum: 1,
        pageSize: 10,
        order_code: '',
        customer_name: '',
        total: 0
      };
      this.getOrderList();
    },

    /**
     * 选择销售订单并关闭弹窗
     * @param {Object} order 选中的订单行数据
     */
    selectOrderAndClose(order) {
      if (!order) {
        return;
      }
      
      // 设置表单中的销售订单相关字段
      this.form.sales_order_id = order.sales_order_id;
      this.form.order_code = order.order_code;
      this.form.customer_id = order.customer_id;
      this.form.customer_code = order.customer_code;
      this.form.customer_name = order.customer_name;
      this.form.recipient = order.customer_person;
      this.form.tel = order.customer_phone;
      this.form.remark = order.remark;
      this.goodsQuery.sales_order_id = order.sales_order_id;
      
      // 生成唯一标识（yyMMddHHmmss格式的日期时间）
      const now = new Date();
      const year = String(now.getFullYear()).slice(-2);
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      const uniqueId = year + month + day + hours + minutes + seconds;
      
      // 生成出库单名称：客户名称+出库单+唯一标识
      this.form.sales_name = order.customer_name + '出库单-' + uniqueId;
      
      // 自动加载销售订单相关的产品明细
      this.loadOrderProducts(order.sales_order_id);
      
      // 关闭销售订单选择弹窗
      this.orderDialogVisible = false;
    },
    
    /**
     * 加载销售订单相关的产品明细
     * @param {String|Number} orderId 销售订单ID
     */
    loadOrderProducts(orderId) {
      this.goodsQuery.sales_order_id = orderId;
      
      // 重置分页到第一页
      this.itemQuery.pageNum = 1;
      
      // 修改查询参数，一次性获取所有数据
      const queryParams = {
        sales_order_id: orderId,
        pageNum: 1,
        pageSize: 999999 // 使用足够大的数值一次性获取所有数据
      };
      
      // 显示加载状态
      const loading = this.$loading({
        lock: true,
        text: '正在加载产品明细，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 获取销售订单相关的产品明细
      selectSalesOrderDetail(queryParams).then(response => {
        loading.close();
        // 清空之前的产品明细
        this.itemList = [];
        
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          // 将获取到的产品明细添加到表格中
          response.rows.forEach(item => {
            const newItem = {
              product_id:item.product_id,
              product_code: item.product_code,
              product_name: item.product_name,
              stock_sfn: item.product_sfn,
              unit: item.product_unit,
              sales_num: item.qty_num || 0,
              remark: item.remark || ''
            };
            
            this.itemList.push(newItem);
          });
          
          this.$message.success(`已加载 ${response.rows.length} 个产品明细`);
        } else {
          this.$message.warning('未找到相关产品明细');
        }
      }).catch(error => {
        loading.close();
        console.error('加载产品明细失败:', error);
        this.$message.error('加载产品明细失败');
      });
    },

    /**
     * 通过销售订单ID获取销售产品信息
     * @param {String|Number} orderId 销售订单ID
     */
    loadOrderProductsByOrderId(orderId) {
      // 重置分页到第一页
      this.itemQuery.pageNum = 1;
        
      // 显示加载状态
        const loading = this.$loading({
          lock: true,
        text: '正在加载销售产品信息...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
      // 调用API获取销售产品信息，一次性获取所有数据
      const queryParams = { 
        sales_order_id: orderId,
        pageNum: 1,
        pageSize: 999999 // 使用足够大的数值一次性获取所有数据
      };
      
      getOutbound(queryParams).then(response => {
          loading.close();
        
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          // 清空当前产品明细
          this.itemList = [];
          
          // 将获取到的产品明细添加到表格中
          response.rows.forEach(item => {
            const newItem = {
              product_id: item.product_id,
              product_code: item.product_code,
              product_name: item.product_name,
              stock_sfn: item.product_sfn,
              unit: item.product_unit,
              sales_num: item.qty_num || 0,
              remark: item.remark || ''
            };
            
            this.itemList.push(newItem);
          });
          
          this.$message.success(`已加载 ${response.rows.length} 个销售产品信息`);
          } else {
          this.$message.warning('未找到相关销售产品信息');
          }
        }).catch(error => {
          loading.close();
        console.error('加载销售产品信息失败:', error);
        this.$message.error('加载销售产品信息失败');
        });
    },

    /**
     * 格式化数字
     */
    formatNumber(value) {
      if (value === null || value === undefined) return '0';
      return Number(value).toLocaleString();
    },
    
    /**
     * 打开客户选择对话框
     */
    handleOpenCustomerDialog() {
      this.customerDialogVisible = true;
      this.getCustomerList();
    },
    
    /**
     * 获取客户列表
     */
    getCustomerList() {
      listCustomer(this.customerQuery).then(response => {
        this.customerList = response.rows || [];
        this.customerQuery.total = response.total || 0;
      }).catch(error => {
        console.error('获取客户列表失败:', error);
        this.$message.error('获取客户列表失败');
      });
    },
    
    /**
     * 搜索客户
     */
    handleCustomerSearch() {
      this.customerQuery.pageNum = 1;
      this.getCustomerList();
    },
    
    /**
     * 重置客户搜索条件
     */
    handleCustomerReset() {
      this.customerQuery = {
        pageNum: 1,
        pageSize: 10,
        customer_code: '',
        customer_name: '',
        total: 0
      };
      this.getCustomerList();
    },
    
    /**
     * 选择客户行
     */
    handleCustomerSelect(row) {
      this.customerSelected = row;
    },
          
    /**
     * 确认选择客户
     */
    confirmCustomerSelect() {
      if (!this.customerSelected) {
        this.$message.warning('请选择一个客户');
        return;
      }
      
      const customer = this.customerSelected;
        
      // 设置表单中的客户相关字段
      this.form.customer_id = customer.customer_id;
      this.form.customer_code = customer.customer_code;
      this.form.customer_name = customer.customer_name;
        
      // 可以自动填充收货地址和联系人等信息
      this.form.recipient = customer.recipient || '';
      this.form.tel = customer.tel || '';
        
      // 关闭客户选择弹窗
      this.customerDialogVisible = false;
    },

    /**
     * 格式化日期时间
     * @param {String|Date} dateTime 日期时间
     * @returns {String} 格式化后的日期时间字符串
     */
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      
      // 格式化为 yyyy-MM-dd HH:mm:ss
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.base-info-card {
  margin-bottom: 20px;
  border-radius: 4px;
  background: #fff;
}

.base-info-title {
  font-weight: bold;
  font-size: 16px;
  padding: 4px 0;
}

.base-info-form {
  padding: 0 10px 0 0;
}

.base-info-form .el-form-item {
  margin-bottom: 16px;
}

.goods-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  margin-top: 20px;
  width: 100%;
  box-sizing: border-box;
}

.goods-section .el-table {
  width: 100% !important;
}

.goods-section .el-table__body-wrapper,
.goods-section .el-table__header-wrapper {
  width: 100% !important;
}

.input-switch-group {
  display: flex;
  align-items: center;
}

.input-switch-group .el-input {
  flex: 1;
}

.switch-label {
  margin-left: 6px;
  color: #909399;
  font-size: 14px;
  white-space: nowrap;
}

@media (max-width: 1200px) {
  .base-info-form .el-col-8 {
    width: 100%;
    max-width: 100%;
    flex: 0 0 100%;
  }
}
</style>

<style>
/* Element UI下拉框样式设置 */
.el-select-dropdown__wrap {
  max-height: 200px !important; /* 这将限制下拉菜单高度，使其只显示约5个选项 */
}

/* 自定义迷你加载样式 */
.mini-loading {
  pointer-events: none !important;
}
.mini-loading .el-loading-mask {
  opacity: 0.3 !important;
}
</style> 